package samsung.sds.userManagement.controller;

import java.io.IOException;
import java.net.UnknownHostException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import samsung.sds.departmentManagement.model.DepartmentEntity;
import samsung.sds.departmentManagement.service.DepartmentManagementService;
import samsung.sds.roleManagement.model.RoleManagementEntity;
import samsung.sds.system.common.baseQuery.model.PageData;
import samsung.sds.system.common.model.QueryParam;
import samsung.sds.system.utils.CommonTools;
import samsung.sds.system.utils.Constants;
import samsung.sds.system.utils.Md5Util;
import samsung.sds.userManagement.model.UserEntity;
import samsung.sds.userManagement.service.UserManagementService;

/**
 * @author hao.wen
 * @createDate 2016-01-08
 * 
 *             userManagement的controller组件
 */
@Controller
@RequestMapping("/userManagement")
public class UserManagementController {

	@Autowired
	private UserManagementService userManagementServiceImpl;

	@Autowired
	private DepartmentManagementService departmentManagementServiceImpl;

	/**
	 * 接收请求，返回userList的jsp页面
	 * 
	 * @param request
	 * @param modelMap
	 * @return
	 */
	@RequestMapping(value = "/userList", method = RequestMethod.POST)
	public String loadList(HttpServletRequest request, ModelMap modelMap,
			String currentPage) {
		String pageType = request.getParameter("pageType");
		modelMap.addAttribute("pageType", pageType);
		return "/userManagement/userList";
	}

	/**
	 * 接收请求，封装参数，返回PagaData对象
	 * 
	 * @param request
	 * @param modelMap
	 * @return
	 */
	@RequestMapping(value = "/getUserList", method = RequestMethod.POST)
	@ResponseBody
	public PageData<UserEntity> getUserList(HttpServletRequest request) {
		String onlineName = "";
		QueryParam param = CommonTools.getQueryParam(request);
		@SuppressWarnings("unchecked")
		List<String> inlineUserNames = (List<String>) request.getSession()
				.getServletContext().getAttribute("INLINE_USERNAMES");
		if (!(inlineUserNames == null || inlineUserNames.isEmpty())) {
			for (String userName : inlineUserNames) {
				onlineName = onlineName + "'" + userName + "',";
			}
			onlineName = onlineName.substring(0, onlineName.lastIndexOf(","));
		} else {
			onlineName = "''";
		}
		param.getQueryCondition().put("inlineUserNames", onlineName);
		PageData<UserEntity> pageData = userManagementServiceImpl
				.queryListPage(param);
		return pageData;
	}

	/**
	 * 加载完addOrUpdateUser.jsp后，执行请求，将数据写入页面。
	 * 
	 * @param request
	 * @param username
	 * @param modelMap
	 * @return
	 */
	@RequestMapping(value = "/userDetails", method = RequestMethod.POST)
	public String creatUserView(HttpServletRequest request, String username,
			ModelMap modelMap) {

		// 根据username查询uesr对象
		UserEntity user = new UserEntity();
		user.setUsername(username);
		user = this.userManagementServiceImpl.findUniqueByProperty(user);

		// 获取所有角色名称，准备发往前端
		List<RoleManagementEntity> roleList = this.userManagementServiceImpl
				.getUserRoles(username);

		// 存入modelMap准备发往前端
		modelMap.addAttribute("roleList", roleList);

		// 判断user对象是否存在，判断当前是新建还是修改
		if (user == null) {
			UserEntity userPosition = new UserEntity();
			userPosition.setUsername(" ");
			modelMap.addAttribute("user", userPosition);
			return "/userManagement/addOrUpdateUser";
		}
		// 设置密码框占位字符
		user.setPassword("***********");
		String dept_name = user.getDept_name();
		// 对存在的部门名进行转义
		if (dept_name != null) {
			user.setDept_name(dept_name.replaceAll("\"", "&quot;").replaceAll("'", "&#39;"));
		}

		// 存入user对象
		modelMap.addAttribute("user", user);

		// 获取当前用户的角色
		List<String> roleArray = userManagementServiceImpl.queryUserRole(user
				.getUsername());
		// 存入modelMap准备发往前端
		modelMap.addAttribute("roleArray", roleArray);

		return "/userManagement/addOrUpdateUser";
	}

	/**
	 * 验证用户名是否重复
	 * 
	 * @param request
	 * @param response
	 * @param username
	 * @param modelMap
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(value = "/checkName", method = RequestMethod.POST)
	@ResponseBody
	public boolean checkName(String username) {

		return userManagementServiceImpl.checkUserNameRepeat(username);
	}

	/**
	 * 添加或修改用户
	 * 
	 * @param request
	 * @param model
	 * @param user
	 * @return
	 */
	@RequestMapping(value = "/addOrUpdateUser", method = RequestMethod.POST)
	@ResponseBody
	public String addOrUpdateUser(HttpServletRequest request, UserEntity user) {

		String optype = request.getParameter("optype");
		if (user == null || optype == null) {
			return Constants.ERRMSG_PARAM_ERROR;
		}

		// 创建新用户
		if (optype.equalsIgnoreCase("create")) {

			int userRlt = this.userManagementServiceImpl.insertEntity(user);

			if (userRlt == 1) {
				return Constants.SUCCESS_CODE;
			} else {
				return Constants.FAILURE_CODE;
			}
			// 修改用户
		} else if (optype.equalsIgnoreCase("update")) {
			int rlt = this.userManagementServiceImpl.updateEntity(user);
			if (rlt == 1) {
				return Constants.SUCCESS_CODE;
			} else {
				return Constants.FAILURE_CODE;
			}
			// 传过来的doType没有匹配上
		} else {
			return Constants.ERRMSG_PARAM_ERROR;
		}
	}

	/**
	 * 删除用户
	 * 
	 * @param request
	 * @param model
	 * @param username
	 * @return
	 */
	@RequestMapping(value = "/deleteUser", method = RequestMethod.POST)
	@ResponseBody
	public String deleteUser(String username) {

		// 若用户名为空返回错误信息
		if (username == null || "".equals(username)) {
			return Constants.ERRMSG_PARAM_ERROR;
		}

		int rlt = userManagementServiceImpl.deleteEntityById(username);

		if (rlt == 1) {
			return Constants.SUCCESS_CODE;
		} else {
			return Constants.FAILURE_CODE;
		}
	}

	/**
	 * 查出所有部门
	 * 
	 * @param request
	 * @param response
	 * @param map
	 * @return
	 */
	@RequestMapping(value = "/queryDepts", method = RequestMethod.POST)
	@ResponseBody
	public List<DepartmentEntity> queryDepartments() {
		QueryParam param = new QueryParam();
		return departmentManagementServiceImpl.queryList(param);

	}

	/**
	 * 检查密码是否改变
	 * 
	 * @param Password
	 * @return
	 */
	@RequestMapping(value = "/checkPassword", method = RequestMethod.POST)
	@ResponseBody
	public boolean checkPassword(String username, String password) {

		return userManagementServiceImpl.checkPassword(username, password);
	}

	/**
	 * 强制用户下线
	 * 
	 * @param createUser
	 * @param request
	 * @param modelMap
	 * @return
	 * @throws UnknownHostException
	 */
	@RequestMapping(value = "/exitUser", method = RequestMethod.POST)
	public String exitUser(String createUser, HttpServletRequest request,
			ModelMap modelMap) throws UnknownHostException {
		HttpSession session = (HttpSession) request.getSession()
				.getServletContext().getAttribute(createUser);
		if (session != null) {
			session.invalidate();
		}
		String pageType = request.getParameter("pageType");
		modelMap.addAttribute("pageType", pageType);
		return "/userManagement/userList";
	}

	/**
	 * 加载完addOrUpdateUser.jsp后，执行请求，将数据写入页面。
	 * 
	 * @param request
	 * @param username
	 * @param modelMap
	 * @return
	 */
	@RequestMapping(value = "/viewPersonalInfo")
	public String viewPersonalInfo(ModelMap modelMap, String tabIndex) {
		// 根据username查询uesr对象
		UserEntity user = new UserEntity();
		user.setUsername(CommonTools.getSessionUserName());
		user = this.userManagementServiceImpl.findUniqueByProperty(user);
		String dept_name = user.getDept_name();
		// 对存在的部门名进行转义
		if (dept_name != null) {
			user.setDept_name(CommonTools.escapeHTMLParam(dept_name));
		}

		UserEntity userForView = new UserEntity();
		// 只传递必要字段
		userForView.setCn_name(user.getCn_name());
		userForView.setDept_name(user.getDept_name());
		userForView.setEmail(user.getEmail());
		userForView.setEmp_code(user.getEmp_code());

		// 存入user对象
		modelMap.addAttribute("user", userForView);
		modelMap.addAttribute("tabIndex", tabIndex);

		return "/userManagement/viewPersonalInfo";
	}

	/**
	 * update user info
	 * 
	 * @param request
	 * @param model
	 * @param user
	 * @return
	 */
	@RequestMapping(value = "/updatePersonalInfo", method = RequestMethod.POST)
	@ResponseBody
	public String updatePersonalInfo(UserEntity user) {
		user.setUsername(CommonTools.getSessionUserName());
		return this.userManagementServiceImpl.updatePersonalInfo(user) == 1 ? Constants.SUCCESS_CODE
				: Constants.FAILURE_CODE;
	}

	/**
	 * update user info
	 * 
	 * @param request
	 * @param model
	 * @param user
	 * @return
	 */
	@RequestMapping(value = "/updatePersonalInfoPwd", method = RequestMethod.POST)
	@ResponseBody
	public String updatePersonalPwd(String pwd_old, String pwd_new) {
		UserEntity userForQuery = new UserEntity();
		userForQuery.setUsername(CommonTools.getSessionUserName());
		UserEntity user = this.userManagementServiceImpl
				.findUniqueByProperty(userForQuery);
		if (!user.getPassword().equalsIgnoreCase(Md5Util.Md5Convert(pwd_old))) {
			return "password mismatch";
		} else {
			UserEntity userForUpdate = new UserEntity();
			userForUpdate.setUsername(CommonTools.getSessionUserName());
			userForUpdate.setPassword(Md5Util.Md5Convert(pwd_new));
			return this.userManagementServiceImpl
					.updatePersonalInfo(userForUpdate) == 1 ? Constants.SUCCESS_CODE
					: Constants.FAILURE_CODE;
		}
	}	
}
